package com.demo.thread.executors;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author peter
 * @date 2022/3/29 0:02
 */
public class ThreadPoolExecutorDemo {

    public static class TargetRunable implements Runnable {
        @Override
        public void run() {
            try {
                Thread.sleep(500);
                System.out.println("线程：" + Thread.currentThread().getId());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        // corePoolSize：核心线程数量，会一直存在，除非allowCoreThreadTimeOut设置为true
        // maximumPoolSize：线程池允许的最大线程池数量
        // keepAliveTime：线程数量超过corePoolSize，空闲线程的最大超时时间
        // unit：超时时间的单位
        // workQueue：工作队列，保存未执行的Runnable 任务
        // threadFactory：创建线程的工厂类
        // handler：当线程已满，工作队列也满了的时候，会被调用。被用来实现各种拒绝策略。
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                2,// 核心线程数
                2,
                60L,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(3),
                new ThreadPoolExecutor.AbortPolicy()
        );

        for (int i = 0; i < 10; i++) {
            threadPoolExecutor.submit(new TargetRunable());
        }

        Thread.sleep(10000);
    }
}
